import {onMounted, reactive, ref, watch, watchEffect} from 'vue';
import { queryInvmbList, queryCmsmwList, addqmsmgItem } from "@api/url/erp/cmsmv";
import notification from "@arco-design/web-vue/es/notification";
export default function importConfig() {
  const base = reactive<any>({
    formRef:null,
    checkParam: {
      mb001: '',
      mb002: '',
      mb003: '',
      jyType: "",
      mw001: '',
      mw002: '',
      mw003: '',
    },
    rules:{
      mb001: [
        {
          required: true,
          message: '品号不可为空',
        },
      ],
      jyType: [
        {
          required: true,
          message: '检验类型不可为空',
        },
      ],
      mw001: [
        {
          required: true,
          message: '工艺不可为空',
        },
      ],
    },
    tableTextData: [
        {
            udf01: '',
            udf02: '',
            mg006: '',
            udf03: '',
            mg009: '1'
        },
    ],
    tableNumData: [
      {
        udf01: '',
        udf02: '',
        udf03: '',
        mg012: '',
        mg013: '',
        mg006: '',
        mg009: '1',
      }
    ],
    cpvisible: false,
    cpLoading: false,
    tableCpData: [],
    cpLimitParam: {
      current: 1,
      size: 10,
      total: 100,
      ph: '',
      pm: ''
    },
    gyvisible: false,
    gyLoading: false,
    tableGyData: [],
    gyLimitParam: {
      current: 1,
      size: 10,
      total: 100,
      gy: ''
    },
    qualityType: [
      { label: '计数', value: '1' },
      { label: '计量', value: '2' }
    ],
  });

  const tableTextRef = ref();
  const tableNumRef = ref();

  //
  const formatQualityType = (val: string) => {
    if(val === '1'){
      return "计数";
    }else{
      return "计量";
    }
  }

  // 插入文本型表格
  const insertEvent = async (row?: any) => {
    const $table = tableTextRef.value
    if ($table) {
      const record = {
        udf01: '',
        udf02: '',
        mg006: '',
        udf03: '',
        mg009: '1',
      };
      base.tableTextData.push(record);
      const { row: newRow } = await $table.insertAt(record, row);
      await $table.setEditCell(newRow, 'name');
    };
  };

  // 侦听文本型
  watch(base.tableTextData,(newVal, oldVal) => {
    let listLastVal = newVal[newVal.length  - 1]
    let flag = true;
    for (let key in listLastVal) {
        if(listLastVal[key] == ''){
            flag = false;
        };
    };
    if(flag){
        insertEvent(-1);
    };
  });

  // 文本型删除列
  const delTextTableCol = (row, rowIndex) => {
    if(rowIndex != (base.tableTextData.length - 1)){
      base.tableTextData.splice(rowIndex, 1);
    }else{
      notification.error("该列为空列不可删除！");
    }
  }


  // 插入数值型表格
  const insertEventNum = async (row?: any) => {
    const $table = tableNumRef.value
    if ($table) {
      const record = {
        udf01: '',
        udf02: '',
        udf03: '',
        mg012: '',
        mg013: '',
        mg006: '',
        mg009: '1',
      };
      base.tableNumData.push(record);
      const { row: newRow } = await $table.insertAt(record, row);
      await $table.setEditCell(newRow, 'name');
    };
  };

  // 侦听数值型
  watch(base.tableNumData,(newVal, oldVal) => {
    let listLastVal = newVal[newVal.length  - 1]
    let flag = true;
    for (let key in listLastVal) {
        if(listLastVal[key] == ''){
            flag = false;
        };
    };
    if(flag){
      insertEventNum(-1);
    };
  });

  // 加载产品
  const getInvmbList = () => {
    base.cpLoading = true;
    const param = {
      current: base.cpLimitParam.current,
      size: base.cpLimitParam.size,
      ph: base.cpLimitParam.ph,
      pm: base.cpLimitParam.pm
    };
    queryInvmbList(param).then((res: any) => {
      // console.log(res);
      if(res.code === 200){
        base.tableCpData = res.data.data;
        base.cpLimitParam.total = res.data.total;
      }else{
        base.tableCpData = [];
        notification.error(res.message);
      };
      base.cpLoading = false;
    });
  };

  // 产品分页
  const getCpTableData = (val) => {
    base.cpLimitParam.current = val.currentPage;
    base.cpLimitParam.size = val.pageSize;
    getInvmbList();
  };

  // 查询产品
  const queryCpFun = () => {
    base.cpLimitParam.current = 1;
    getInvmbList();
  };

  // 产品表格
  const tableCpRef = ref();


  // 确认选择产品
  const cphandleOk = () => {
    getRadioEvent(tableCpRef);
  };

  // 获取选中
  const getRadioEvent = (elm) => {
    const $table = elm.value
    if ($table) {
      const currRow = $table.getRadioRecord()
      // console.log(currRow);
      base.checkParam.mb001 = currRow.mb001;
      base.checkParam.mb002 = currRow.mb002;
      base.checkParam.mb003 = currRow.mb003;
    };
  };


  // 加载工艺
  const getCmsmwList = () => {
    base.gyLoading = true;
    const param = {
      current: base.gyLimitParam.current,
      size: base.gyLimitParam.size,
      gy: base.gyLimitParam.gy
    };
    queryCmsmwList(param).then((res: any) => {
      if(res.code === 200){
        base.tableGyData = res.data.data;
        base.gyLimitParam.total = res.data.total;
      }else{
        base.tableGyData = [];
        notification.error(res.message);
      }
      base.gyLoading = false;
    })

  };

  // 查询工艺
  const queryGyFun = () => {
    base.gyLimitParam.current = 1;
    getCmsmwList();
  };

  // 工艺表格
  const tableGyRef = ref();

  // 工艺分页
  const getGyTableData = (val) => {
    base.gyLimitParam.current = val.currentPage;
    base.gyLimitParam.size = val.pageSize;
    getCmsmwList();
  }

  // 确认选择工艺
  const gyhandleOk = () => {
    getRadioEventGy(tableGyRef);
  }

  // 获取选中
  const getRadioEventGy = (elm) => {
    const $table = elm.value
    if ($table) {
      const currRow = $table.getRadioRecord()
      // console.log(currRow);
      base.checkParam.mw001 = currRow.mw001;
      base.checkParam.mw002 = currRow.mw002;
      base.checkParam.mw003 = currRow.mw003;
    };
  };

  // 数字型删除列
  const delNumTableCol = (row, rowIndex) => {
    if(rowIndex != (base.tableNumData.length - 1)){
      base.tableNumData.splice(rowIndex, 1);
    }else{
      notification.error("该列为空列不可删除！");
    }
  }


  // 录入检验
  const insertQualityFun = () => {
    base.formRef.validate((obj) => {
      if (!obj) {
        if(base.tableTextData.length > 1 || base.tableNumData.length > 1){
          let textObjList = [];
          for(let i = 0 ; i < base.tableTextData.length - 1; i++){
            const textObj = {
              mg002: base.checkParam.mb001.trim(),
              mg006: base.tableTextData[i].mg006,
              mg008: base.checkParam.mw001,
              mg011: "4",
              mg020: base.checkParam.jyType,
              udf01: base.tableTextData[i].udf01,
              udf02: base.tableTextData[i].udf02,
              udf03: base.tableTextData[i].udf03,
              udf08: base.checkParam.mw003,
              udf09: base.checkParam.mw002,
              mg009: base.tableTextData[i].mg009,
              udf06: base.tableTextData[i].udf06
            };
            textObjList.push(textObj as never);
          };
          let numObjList = [];
          for(let i = 0 ; i < base.tableNumData.length - 1; i++){
            const numObj = {
              mg002: base.checkParam.mb001,
              mg006: base.tableNumData[i].mg006,
              mg008: base.checkParam.mw001,
              mg011: "3",
              mg020: base.checkParam.jyType,
              udf01: base.tableNumData[i].udf01,
              udf02: base.tableNumData[i].udf02,
              udf03: base.tableNumData[i].udf03,
              udf08: base.checkParam.mw003,
              udf09: base.checkParam.mw002,
              mg009: base.tableNumData[i].mg009,
              mg012: base.tableNumData[i].mg012,
              mg013: base.tableNumData[i].mg013,
            };
            numObjList.push(numObj as never);
          };

          // console.log(textObjList);
          // console.log(numObjList);
          const paramList = [...textObjList,...numObjList];
          addqmsmgItem(paramList).then((res: any) => {
            if(res.code === 200){
              notification.success("录入成功");
              history.go(-1);
            }else{
              notification.error(res.message);
            }
          })
        }else{
          notification.error("请输入检验项目！");
        }
      }
    });
  }

  onMounted(() => {
    getInvmbList();
    getCmsmwList();

  })

  return {
    base,
    tableTextRef,
    tableNumRef,
    getCpTableData,
    tableCpRef,
    cphandleOk,
    queryCpFun,
    gyhandleOk,
    queryGyFun,
    tableGyRef,
    getGyTableData,
    insertQualityFun,
    formatQualityType,
    delTextTableCol,
    delNumTableCol,
  };
}
